/**
 *       Copyright (c) 2012 Lukas Zaruba
 *
 *   This file is part of Robot Playground.
 *
 *   Robot Playground is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   Robot Playground is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with Robot Playground. If not, see <http://www.gnu.org/licenses/>.
 */
package net.zarubsys.commons.scripting.functions.strings;

import java.util.Iterator;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import net.zarubsys.commons.scripting.IScriptFunction;
import net.zarubsys.commons.scripting.ParsedStatement;
import net.zarubsys.commons.scripting.ScriptingEnvironment;
import net.zarubsys.commons.scripting.ScriptingException;
import net.zarubsys.commons.utils.StringUtils;

import org.w3c.dom.Node;

/**
 * Based on scripting language from Media Solutions Slovakia, a.s.
 * @author Lukas Zaruba, lukas.zaruba@gmail.com
 */
public class XPathValueFunction implements IScriptFunction {

    public String getName() {
        return "xPathValue";
    }

    public int getMinArgsNum() {
        return 2;
    }

    public int getMaxArgsNum() {
        return 2;
    }

    public Object execute(ScriptingEnvironment env, List<ParsedStatement> args) throws ScriptingException {
        Iterator<ParsedStatement> iter = args.iterator();
        Object rawNode = iter.next().execute(env);
        if (!(rawNode instanceof Node)) {
        	throw new IllegalArgumentException("First argument must be an instance of Node! Value: " + rawNode);
        }
        Node rootNode = (Node) rawNode;
        String xPathLoc = StringUtils.toString(iter.next().execute(env));
        
        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();
        XPathExpression xPathExpression;
        
        try {
			xPathExpression = xPath.compile(xPathLoc);
		} catch (XPathExpressionException e) {
			throw new ScriptingException("XPath Expression: '" + xPathLoc + "' cannot be compiled.", env.getCurrentScriptLocator());
		}
		
		try {
			Object value = xPathExpression.evaluate(rootNode);
			return value;
		} catch (XPathExpressionException e) {
			throw new ScriptingException("Error executing XPath Expression '" + xPathLoc + "' on DOM.", env.getCurrentScriptLocator());
		} 
    }

}
